package com.example.desksginktapp.bases

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.os.SystemClock
import com.example.baselibrary.bases.Constants
import com.example.baselibrary.utlis.AppCache
import com.example.baselibrary.utlis.ContextUtils
import com.example.baselibrary.utlis.GlobalTimer
import com.example.baselibrary.utlis.Md5Util
import com.example.baselibrary.utlis.RestartHelper
import com.example.httplibrary.https.RetrofitClient
import com.xuexiang.xui.XUI


/**
 * Base application class that can be used as the foundation for the app.
 * This class can be extended to add application-level initialization logic.
 */
open class BaseApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        initializeApp()
    }



    protected open fun initializeApp() {
        // 这个是时间计时器，默认是开启的
        GlobalTimer.init(this)
        GlobalTimer.start()
        //全局引入
        ContextUtils.init(this)
        // 初始化缓存管理器
        AppCache.init(this)
        //开启UI框架
        XUI.init(this); //初始化UI框架
        XUI.debug(true);  //开启UI框架调试日志
        // 注册生命周期监听
        registerActivityLifecycleCallbacks(AppLifecycleTracker())
        // 注册崩溃后自动重启
        Thread.setDefaultUncaughtExceptionHandler { _, e ->
            RestartHelper.scheduleDelayedRestart(
                context = this,
                delayMillis = 2000,
                reason = "CRASH"
            )
        }
        RestartHelper.scheduleBootStart(this)

        // 开机时初始化必要组件
        if (isAfterBoot()) {
            initAfterBoot()
        }
        preparBaseUrl()
        preparHeader()
    }

    private fun preparBaseUrl() {
        AppCache.get()?.getAsString(Constants.URL)?.let {
            RetrofitClient.setBaseUrl(it)
        }
    }

    private fun preparHeader() {
        // 设置基础请求头提供者
        RetrofitClient.setHeadersProvider {
            val timestamp = System.currentTimeMillis().toString()
            val sign = Md5Util.encrypt( "akjndouahoqwocihugwniasjo" + timestamp)

            mapOf(
                "appKey" to "kahdhohoqi",
                "timeStamp" to timestamp,
                "sign" to sign
            )
        }
    }

    override fun onTerminate() {
        super.onTerminate()
        GlobalTimer.stop()
    }

    private fun isAfterBoot(): Boolean {
        val bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime()
        return System.currentTimeMillis() - bootTime < 60_000 // 开机1分钟内
    }

    private fun initAfterBoot() {
        // 初始化后台服务等
    }

    private inner class AppLifecycleTracker : ActivityLifecycleCallbacks {
        private var activityCount = 0

        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            activityCount++
        }

        override fun onActivityDestroyed(activity: Activity) {
            activityCount--
            if (activityCount == 0) {
                // 所有Activity关闭时，启动30秒延迟重启
                RestartHelper.scheduleDelayedRestart(
                    context = activity.applicationContext,
                    delayMillis = 30_000,  // 30秒
                    showToast = true       // 显示提示
                )
            }
        }

        // 其他空实现
        override fun onActivityStarted(activity: Activity) {}
        override fun onActivityResumed(activity: Activity) {}
        override fun onActivityPaused(activity: Activity) {}
        override fun onActivityStopped(activity: Activity) {}
        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
    }
}